package com.itlong.cloud.controller.project;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.itlong.cloud.POJO.DTO.operate.*;
import com.itlong.cloud.POJO.DTO.property.PropertyProjectGetBuildSimpleInfoDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyProjectGetRoomSimpleInfoDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyProjectGetUnitSimpleInfoDTO;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.PO.OperateUserInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.*;
import com.itlong.cloud.POJO.VO.property.PropertyProjectBuildSimpleInfoVO;
import com.itlong.cloud.POJO.VO.property.PropertyProjectRoomSimpleInfoVO;
import com.itlong.cloud.POJO.VO.property.PropertyProjectUnitSimpleInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.annotation.UnParamEncrypt;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.ErrorCode;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.paymenthub.IPaymentTradeServiceClient;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.project.property.IPropertyBuildInfoServiceClient;
import com.itlong.cloud.project.property.IPropertyRoomInfoServiceClient;
import com.itlong.cloud.project.property.IPropertyUnitInfoServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.operate.IOperateUserInfoServiceClient;
import com.itlong.cloud.user.operate.IOperateUserManageServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.Request;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 *      运营-项目管理控制器
 * </desc>
 *
 * @createDate 2017-10-10.
 */
@RestController
@RequestMapping("/project")
public class OperateProjectController extends BaseController {
    private  static final Logger LOG = LoggerFactory.getLogger(OperateProjectController.class);

    //取消人脸信息配置中的人脸库为不是必填项所需的常量。
    @Value("${" + PlatformConstants.PM_DEFAULT_FACE_LIBRARY_APPID + "}")
    String appId;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    IPaymentTradeServiceClient iPaymentTradeServiceClient;

    @Autowired
    IOperateUserManageServiceClient iOperateUserManageServiceClient;

    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;

    @Autowired
    IPropertyBuildInfoServiceClient iPropertyBuildInfoServiceClient;

    @Autowired
    IPropertyUnitInfoServiceClient iPropertyUnitInfoServiceClient;

    @Autowired
    IPropertyRoomInfoServiceClient iPropertyRoomInfoServiceClient;

    @Autowired
    IOperateUserInfoServiceClient iOperateUserInfoServiceClient;

    /**
     * <desc>
     *      严格验证项目编号有效性（8位数字）
     * <desc/>
     *
     * @param projectId 项目编号
     * @return
     * @author Chunjian.G
     * @createDate 2017-10-13
     */
    private boolean validProjectIdStrict(String projectId){
        if (StringUtils.isBlank(projectId) || !projectId.matches("[0-9]{8}")){
            return false;
        }
        return true;
    }

    /**
    * <desc>
    *      添加单个项目
    * <desc/>
    *
    * @param saveDTO 新增项目信息
    * @return
    * @author caoshuai
    * @createDate 2020-9-16
    */
    @LoggerInfo(operateDesc = LogDescConstant.PROJECT_SAVE_LOG_DESC)
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object saveProject(OperateProjectSaveDTO saveDTO){
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        saveDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateProjectSaveDTO.class,request);
        String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
        saveDTO.setLoginUserId(myUserName);
        String ip = HttpProtocolUtil.getIpAddr(request);
        saveDTO.setIp(ip);
        try {
            //判断合法性
            if (null == saveDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
//            //公钥不合法
//            if (StringUtils.isBlank(saveDTO.getPubKey())){
//                return new MessageVO(OperateErrorCodeEnum.PROJECT_PUB_KEY_EMPTY_ERR.getErrorCode());
//            }
            //状态不合法
            if (null == saveDTO.getStatus() || (DataStatusEnum.NORMAL.getType().equals(saveDTO.getStatus()) &&
                 DataStatusEnum.BAN.getType().equals(saveDTO.getStatus()))){
                return new MessageVO(OperateErrorCodeEnum.PROJECT_STATUS_INVALID_ERR.getErrorCode());
            }

            //项目编号不合法或已存在
//            if (!validProjectIdStrict(saveDTO.getProjectId())){
//                return new MessageVO((OperateErrorCodeEnum.PROJECT_ID_INVALID_ERR.getErrorCode()));
//            }else if (iOperateProjectServiceClient.checkProjectExist(saveDTO.getProjectId()) > 0){
//                return new MessageVO(OperateErrorCodeEnum.PROJECT_EXIST.getErrorCode());
//            }
            saveDTO.setSecurityCode((Math.random() + "").substring(2, 10));
            Integer res = iOperateProjectServiceClient.saveProject(saveDTO);

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), res);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目管理_添加项目add】添加项目失败", e);
        }
    }

    /**
     * <desc>
     *      更新单个项目信息
     * <desc/>
     *
     * @param updateDTO 项目更新信息
     * @return
     * @author Chunjian.G
     * @createDate 2017-10-11
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PROJECT_UPDATE_LOG_DESC)
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object updateProject(OperateProjectUpdateDTO updateDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            updateDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateProjectUpdateDTO.class,request);
            String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
            updateDTO.setLoginUserId(myUserName);
            String ip = HttpProtocolUtil.getIpAddr(request);
            updateDTO.setIp(ip);
            LOG.info("【updateProject】{} {} {}", updateDTO, myUserName, ip);
            //判断参数合法性
            if (null == updateDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //项目编号不合法
            if (!validProjectIdStrict(updateDTO.getProjectId())){
                return new MessageVO(OperateErrorCodeEnum.PROJECT_ID_INVALID_ERR.getErrorCode());
            }
            //项目状态
            if (null != updateDTO.getStatus() && (updateDTO.getStatus() != DataStatusEnum.NORMAL.getType()
                    && updateDTO.getStatus() != DataStatusEnum.BAN.getType())){
                return new MessageVO(OperateErrorCodeEnum.PROJECT_STATUS_INVALID_ERR.getErrorCode());
            }
            //更新方式:0项目基础信息更新
            if ("0".equals(updateDTO.getUpdateFlag())) {
                //项目编号不合法
                if (!validProjectIdStrict(updateDTO.getProjectId())){
                    return new MessageVO(OperateErrorCodeEnum.PROJECT_ID_INVALID_ERR.getErrorCode());
                }
                //项目状态
                if (null != updateDTO.getStatus() && (updateDTO.getStatus() != DataStatusEnum.NORMAL.getType()
                        && updateDTO.getStatus() != DataStatusEnum.BAN.getType())){
                    return new MessageVO(OperateErrorCodeEnum.PROJECT_STATUS_INVALID_ERR.getErrorCode());
                }
            }
            //判断是否启用人脸识别
            if((null!=updateDTO.getIsFaceRecognition())&&(1==updateDTO.getIsFaceRecognition())){
                //判断人脸库是否有选择 如果没有选择给默认值
                //判断人脸应用编号
                if (StringUtils.isBlank(updateDTO.getAppId())|| !updateDTO.getAppId().matches("[0-9]{8}")){
                    updateDTO.setAppId(appId);
                }else {
                    //判断人脸应用编号
                    if(!updateDTO.getAppId().matches("[0-9]{8}")){
                        return new MessageVO(OperateErrorCodeEnum.FACE_APP_ID_INVALID_ERR.getErrorCode());
                    }
                    //判断人脸识别率
                    if(StringUtils.isBlank(updateDTO.getFaceScore())){
                        return new MessageVO(OperateErrorCodeEnum.FACE_SCORE_INVALID_ERR.getErrorCode());
                    }
                }

              /*  //判断人脸应用编号
                if(StringUtils.isBlank(updateDTO.getAppId()) || !updateDTO.getAppId().matches("[0-9]{8}")){
                    return new MessageVO(OperateErrorCodeEnum.FACE_APP_ID_INVALID_ERR.getErrorCode());
                }
                //判断是否启用人脸识别
                if((null!=updateDTO.getIsFaceRecognition())&&(1==updateDTO.getIsFaceRecognition())){
                    //判断人脸应用编号
                    if(StringUtils.isBlank(updateDTO.getAppId()) || !updateDTO.getAppId().matches("[0-9]{8}")){
                        return new MessageVO(OperateErrorCodeEnum.FACE_APP_ID_INVALID_ERR.getErrorCode());
                    }
                    //判断人脸识别率
                    if(StringUtils.isBlank(updateDTO.getFaceScore())){
                        return new MessageVO(OperateErrorCodeEnum.FACE_SCORE_INVALID_ERR.getErrorCode());
                    }

                }*/
            }
            //收费模式和物业增值不能同时开启
            ProjectPO oldProject = iOperateProjectServiceClient.getOneProject(updateDTO.getProjectId());
            if(updateDTO.getChargeMode() != null && updateDTO.getChargeMode()==2 && oldProject.getPropertyValueOpen()==1){
                return new MessageVO(OperateErrorCodeEnum.PROJECT_FUNCITON_ISNOT_ALLOWD.getErrorCode());
            }
            Integer result = iOperateProjectServiceClient.updateProject(updateDTO);
            MessageVO messageVO = new MessageVO(updateDTO.getProjectId(),BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
            return  messageVO;
        }catch (Exception e){
            e.printStackTrace();
            throw new DataAccessException("【运营_项目管理_更新项目update】更新项目信息失败", e);
        }
    }

     /**
      * <desc>
      *      分页获取项目信息（简易信息）
      * <desc/>
      *
      * @param pageDTO 分页获取项目信息条件
      * @return
      * @author Chunjian.G
      * @createDate 2017-10-10
      */
    @RequestMapping(value = "/getPage",method = RequestMethod.POST)
    @ResponseBody
    public Object getPage(OperateProjectGetPageDTO pageDTO){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateProjectGetPageDTO.class,request);
            //独立开发者调整为可多个对应一个项目
            if (pageDTO.getPropertyRoleId() != null && "4".equals(pageDTO.getPropertyRoleId())) {
                pageDTO.setPropertyRoleId(null);
            }
            Page<OperateProjectVO> page = iOperateProjectServiceClient.getPage(pageDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目管理_项目getPage】获取分页列表失败", e);
        }
        return  messageVO;
    }

     /**
      * <desc>
      *      获取单个项目详情
      * <desc/>
      *
      * @param projectId 项目编号
      * @return
      * @author Chunjian.G
      * @createDate 2017-10-11
      */
    @RequestMapping(value = "/getDetail", method = RequestMethod.POST)
    @ResponseBody
    public Object getDetail(String projectId){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            //参数判断
            if (!validProjectIdStrict(projectId)){
                return new MessageVO(OperateErrorCodeEnum.PROJECT_ID_INVALID_ERR.getErrorCode());
            }

            OperateProjectDetailVO detailVO = iOperateProjectServiceClient.getDetail(projectId);
            Integer elevator = iPropertyEquipServiceClient.getDeviceCountByBatchNumber(projectId, PropertyEquipTypeEnum.ELEVATOR.getType()+"","");
            Integer entrance = iPropertyEquipServiceClient.getDeviceCountByBatchNumber(projectId, PropertyEquipTypeEnum.ENTRANCE.getType()+"","");
            Integer talk = iPropertyEquipServiceClient.getDeviceCountByBatchNumber(projectId, PropertyEquipTypeEnum.CLOUD_INTERCOM.getType()+"","");
            Integer pad = iPropertyEquipServiceClient.getDeviceCountByBatchNumber(projectId, "4","");
            if(detailVO!=null){
                detailVO.setElevatorCount(elevator==null?0:elevator);
                detailVO.setEntranceCount(entrance==null?0:entrance);
                detailVO.setIntercomCount(talk==null?0:talk);
                detailVO.setFacePadCount(pad==null?0:pad);
            }
            MessageVO messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), detailVO);
            return messageVO;
        }catch (Exception e){
            throw  new DataAccessException("【运营_项目管理_查看项目getDetail】获取项目详情失败", e);
        }
    }

    /**
     * <desc>
     *      查询单个项目的关联设备列表
     * <desc/>
     *
     * @param projectId 项目编号
     * @return
     * @author Chunjian.G
     * @createDate 2017-10-13
     */
    @RequestMapping(value = "/getProjectProduct", method = RequestMethod.POST)
    @ResponseBody
    public Object getRelatedProducts(String projectId){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            //参数判断
            if (!validProjectIdStrict(projectId)){
                return new MessageVO(OperateErrorCodeEnum.PROJECT_ID_INVALID_ERR.getErrorCode());
            }

            List<OperateProjectRelatedProductVO> productVOS = iOperateProjectServiceClient.getRelatedProducts(projectId);
            Map<String, Object> results = new HashMap<>();
            results.put("totalNumber", productVOS.size());
            results.put("rows", productVOS);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), results);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目管理_查看关联设备getProjectProduct】获取项目关联设备失败", e);
        }
    }

    /**
     * <desc>
     *      更新单个项目的关联设备列表
     * <desc/>
     *
     * @param projectId 项目编号
     * @param relatedProducts 项目关联设备列表JsonArray
     * @return
     * @author Chunjian.G
     * @createDate 2017-10-13
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PROJECT_UPDATE_RELATED_PRODUCTS_LOG_DESC)
    @RequestMapping(value = "/updateProjectProduct", method = RequestMethod.POST)
    @ResponseBody
    public Object saveRelatedProducts(String projectId, String relatedProducts){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            relatedProducts=request.getAttribute("relatedProducts")==null?null:request.getAttribute("relatedProducts").toString();
            //参数判断
            if (!validProjectIdStrict(projectId)){
                return new MessageVO(OperateErrorCodeEnum.PROJECT_ID_INVALID_ERR.getErrorCode());
            }
            List<OperateProjectRelatedProductSaveDTO> saveDTOS = new ArrayList<>();
            if (!StringUtils.isBlank(relatedProducts)){
                try {
                    saveDTOS = JSONArray.parseArray(relatedProducts, OperateProjectRelatedProductSaveDTO.class);
                }catch (Exception ex){
                    return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
                }
            }

            Integer result = iOperateProjectServiceClient.saveRelatedProducts(projectId, saveDTOS);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目管理_更新关联设备updateProjectProduct】更新项目关联设备失败", e);
        }
    }

    /**
     * <desc>
     *      获取项目分配列表
     * </desc>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2017/10/12
     */
    @RequestMapping(path = "getAllotProjectPage",method = RequestMethod.POST)
    @ResponseBody
    public Object getAllotProjectPage(OperateAllotProjectDTO pageDTO){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO=HttpProtocolUtil.parseRequestParamToDTO(OperateAllotProjectDTO.class,request);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),
                    iOperateProjectServiceClient.getAllotProjectPage(pageDTO));
        }catch (Exception e){
            throw new DataAccessException("【运营_项目管理_项目getProjectList】获取项目下拉列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取运营首页城市排行、通行方式等
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2019/10/31
     */
    @RequestMapping(path = "getProjectInfo",method = RequestMethod.POST)
    @ResponseBody
    public Object getProjectInfo(){
        MessageVO messageVO;
        try{
            //获取城市项目排行
            OperateProjectStatisticInfoVO operateProjectStatisticInfoVO=iOperateProjectServiceClient.getCityProjectRank();
            //获取通行记录方式
            operateProjectStatisticInfoVO.setOpenTypeRankList(iOperateProjectServiceClient.getPassTypePercent());
            //获取注册用户量
            operateProjectStatisticInfoVO.setRegisterUserCount(iOperateUserManageServiceClient.getPageCount());
            //获取订单总金额
            operateProjectStatisticInfoVO.setPriceCount(iPaymentTradeServiceClient.getOperatePaymentTradePriceCount());
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),operateProjectStatisticInfoVO);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目管理_项目getProjectInfo】运营首页获取项目相关信息失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      根据查询条件查询今日/本周/本月的用户活跃度
     * </desc>
     *
     * @param timeFlag
     * @return
     * @Author Zhu.yj
     * @createDate  2019/10/31
     */
    @RequestMapping(path = "getActiveUser",method = RequestMethod.POST)
    @ResponseBody
    public Object getActiveUser(String timeFlag,String searchTime,String token){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            timeFlag=request.getAttribute("timeFlag")== null ? null: request.getAttribute("timeFlag").toString();
            searchTime=request.getAttribute("searchTime")== null ? null: request.getAttribute("searchTime").toString();
            token= request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            OperateUserInfoPO userInfoPO=iOperateUserInfoServiceClient.retrieve(token);
            if(StringUtils.isBlank(timeFlag)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //未传入时间参数时，默认以当前时间为查询条件
            if(StringUtils.isBlank(searchTime)){
                SimpleDateFormat dateFormat=new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
                searchTime=dateFormat.format(new Date());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iOperateUserManageServiceClient.getActiveUser(timeFlag,searchTime,userInfoPO.getUserId()));
        } catch (Exception e) {
            throw new DataAccessException("【运营_项目管理_getActiveUser】获取用户活跃信息失败",e);
        }
    }

    /**
     * <desc>
     *      分页查询指定项目下的楼栋简单信息（楼栋id ,楼栋名称）列表
     * </desc>
     *
     * @param propertyProjectGetBuildSimpleInfoDTO 查询楼栋简单信息（楼栋ID，楼栋名称）数据传输对象
     * @return 楼栋简单信息（楼栋id ,楼栋名称）列表
     * @author LewisLouis
     * @createDate 2017-09-28
     */
    @RequestMapping(path = "/getBuildList", method = RequestMethod.POST)
    @ResponseBody
    public Object getPageBuildSimpleInfoList(PropertyProjectGetBuildSimpleInfoDTO propertyProjectGetBuildSimpleInfoDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyProjectGetBuildSimpleInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectGetBuildSimpleInfoDTO.class, request);
            //判断参数合法性
            if (null == propertyProjectGetBuildSimpleInfoDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //项目编号不能为空
            if ((StringUtils.isBlank(propertyProjectGetBuildSimpleInfoDTO.getProjectId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            //分页查询楼栋简单信息列表
            Page<PropertyProjectBuildSimpleInfoVO> page = iPropertyBuildInfoServiceClient.getPageBuildSimpleInfoList(propertyProjectGetBuildSimpleInfoDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);


        } catch (Exception e) {
            throw new DataAccessException("【运营_项目_楼栋信息】分页查询楼栋简单信息列表失败", e);
        }
    }

    /**
     * <desc>
     *      分页查询指定楼栋下的单元简单信息（单元id ,单元名称）列表
     * </desc>
     *
     * @param propertyProjectGetUnitSimpleInfoDTO 查询单元简单信息（单元ID，单元名称）数据传输对象
     * @return MessageVO 标准格式化响应结果（含单元简单信息（单元id ,单元名称）列表）
     * @author LewisLouis
     * @createDate 2017-09-28
     */
    @RequestMapping(path = "/getUnitList", method = RequestMethod.POST)
    @ResponseBody
    public Object getPageUnitSimpleInfoList(PropertyProjectGetUnitSimpleInfoDTO propertyProjectGetUnitSimpleInfoDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyProjectGetUnitSimpleInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectGetUnitSimpleInfoDTO.class, request);
            //判断参数合法性
            if (null == propertyProjectGetUnitSimpleInfoDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //楼栋编号不能为空
            if ((StringUtils.isBlank(propertyProjectGetUnitSimpleInfoDTO.getBuildId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_BUILD_ID_EMPTY_ERR.getErrorCode());
            }
            //分页查询单元简单信息列表
            Page<PropertyProjectUnitSimpleInfoVO> page = iPropertyUnitInfoServiceClient.getPageUnitSimpleInfoList(propertyProjectGetUnitSimpleInfoDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);


        } catch (Exception e) {
            throw new DataAccessException("【运营_项目_单元信息】分页查询单元简单信息列表失败", e);
        }
    }

    /**
     * <desc>
     *      分页查询指定单元下的房屋简单信息（房屋id ,房屋名称）列表
     * </desc>
     *
     * @param propertyProjectGetRoomSimpleInfoDTO 查询房屋简单信息（房屋ID，房屋名称）数据传输对象
     * @return MessageVO 标准格式化响应结果
     * @author LewisLouis
     * @createDate 2017-09-28
     */
    @RequestMapping(path = "/getRoomList", method = RequestMethod.POST)
    @ResponseBody
    public Object getPageRoomSimpleInfoList(PropertyProjectGetRoomSimpleInfoDTO propertyProjectGetRoomSimpleInfoDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyProjectGetRoomSimpleInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectGetRoomSimpleInfoDTO.class, request);
            //判断参数合法性
            if (null == propertyProjectGetRoomSimpleInfoDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //单元ID不能为空
            if ((StringUtils.isBlank(propertyProjectGetRoomSimpleInfoDTO.getUnitId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_ID_EMPTY_ERR.getErrorCode());
            }
            //分页查询房屋简单信息列表
            Page<PropertyProjectRoomSimpleInfoVO> page = iPropertyRoomInfoServiceClient.getPageRoomSimpleInfoList(propertyProjectGetRoomSimpleInfoDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);


        } catch (Exception e) {
            throw new DataAccessException("【运营_项目_房屋信息】分页查询房屋简单信息列表失败", e);
        }
    }

    /**
     * <desc>
     *      获取证书列表
     * </desc>
     *
     * @param operateLicenseDTO 参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/9/17
     */
    @RequestMapping(value = "getLicenseDetail", method = RequestMethod.POST)
    public Object getLicenceDetail(OperateLicenseDTO operateLicenseDTO, HttpServletRequest request){
        try {
            operateLicenseDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateLicenseDTO.class, request);
            if (operateLicenseDTO == null || StringUtils.isBlank(operateLicenseDTO.getProjectId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            OperateLicenseAllInfoVO licenseDetailVOS = iOperateProjectServiceClient.getLicenseDetail(operateLicenseDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),licenseDetailVOS);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目_证书管理】获取证书列表失败", e);
        }
    }

    /**
     * <desc>
     *      保存电脑特征码
     * </desc>
     *
     * @param operateLicenseDTO 特征码相关信息
     * @return
     * @Author Zhu.yj
     * @createDate  2020/9/17
     */
    @LoggerInfo(operateDesc = LogDescConstant.OPERATE_SAVE_PC_INFO_LOG_DESC)
    @RequestMapping(value = "savePCInfo", method = RequestMethod.POST)
    public Object savePCInfo(OperateLicenseDTO operateLicenseDTO, HttpServletRequest request){
        try {
            operateLicenseDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateLicenseDTO.class, request);
            String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
            if (operateLicenseDTO == null || StringUtils.isBlank(operateLicenseDTO.getPcInfo()) || StringUtils.isBlank(operateLicenseDTO.getProjectId())
                    || StringUtils.isBlank(myUserName) || StringUtils.isBlank(operateLicenseDTO.getOperateFunction()) || StringUtils.isBlank(operateLicenseDTO.getOperateWay())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            operateLicenseDTO.setLoginUserId(myUserName);
            String ip = HttpProtocolUtil.getIpAddr(request);
            operateLicenseDTO.setIp(ip);
            return iOperateProjectServiceClient.savePcInfo(operateLicenseDTO);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目_证书管理】保存电脑特征码失败", e);
        }
    }

    /**
     * <desc>
     *      更新特征码状态
     * </desc>
     *
     * @param operateLicenseDTO 参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/9/18
     */
    @LoggerInfo(operateDesc = LogDescConstant.OPERATE_UPDATE_PC_INFO_STATUS_LOG_DESC)
    @RequestMapping(value = "updatePCInfoStatus", method = RequestMethod.POST)
    public Object updatePCInfoStatus(OperateLicenseDTO operateLicenseDTO, HttpServletRequest request){
        try{
            operateLicenseDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateLicenseDTO.class, request);
            String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
            if (operateLicenseDTO == null || StringUtils.isBlank(operateLicenseDTO.getPcInfo()) || operateLicenseDTO.getStatus() == null
                    || StringUtils.isBlank(myUserName) || StringUtils.isBlank(operateLicenseDTO.getOperateFunction()) || StringUtils.isBlank(operateLicenseDTO.getOperateWay()) || StringUtils.isBlank(operateLicenseDTO.getProjectId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            operateLicenseDTO.setLoginUserId(myUserName);
            String ip = HttpProtocolUtil.getIpAddr(request);
            operateLicenseDTO.setIp(ip);
            if (!NumberHandlerUtil.isInRange(operateLicenseDTO.getStatus(), 1,2)){
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            iOperateProjectServiceClient.updatePCStatus(operateLicenseDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_项目_证书管理】更改电脑特征码状态失败", e);
        }
    }

    /**
     * <desc>
     *      获取业务日志分页列表
     * </desc>
     *
     * @param operateLicenseDTO 查询参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/9/18
     */
    @RequestMapping(value = "getLogPage", method = RequestMethod.POST)
    public Object getLogPage(OperateLicenseDTO operateLicenseDTO, HttpServletRequest request){
        try{
            operateLicenseDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateLicenseDTO.class, request);
            if (operateLicenseDTO == null || StringUtils.isBlank(operateLicenseDTO.getProjectId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Page<OperateProjectLogPageVO> page = iOperateProjectServiceClient.getLogPage(operateLicenseDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目_证书管理】获取业务日志分页列表失败", e);
        }
    }

    /**
     * <desc>
     *      在线查询证书
     * </desc>
     *
     * @param operateLicenseDTO 查询参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/9/25
     */
    @UnAuthAccessRequired
    @RequestMapping(value = "/online/getLicense", method = RequestMethod.POST)
    public Object getLicense(OperateLicenseDTO operateLicenseDTO, HttpServletRequest request){
        try {
            operateLicenseDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateLicenseDTO.class, request);
            if (operateLicenseDTO == null || StringUtils.isBlank(operateLicenseDTO.getProjectId()) || StringUtils.isBlank(operateLicenseDTO.getSecurityCode())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String ip = HttpProtocolUtil.getIpAddr(request);
            operateLicenseDTO.setIp(ip);
            OperateOnlineLicenseInfoVO operateOnlineLicenseInfoVO = iOperateProjectServiceClient.getLicense(operateLicenseDTO);
            if (operateOnlineLicenseInfoVO == null){
                return new MessageVO(OperateErrorCodeEnum.OPERATE_PROJECT_OR_SECURITY_CODE_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(operateOnlineLicenseInfoVO.getLicenseInfo())){
                return new MessageVO(OperateErrorCodeEnum.OPERATE_NONE_LICENSE_ERROR.getErrorCode());
            }
            operateOnlineLicenseInfoVO.setLicenseInfo(null);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), operateOnlineLicenseInfoVO);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目_在线查询证书网站】在线查询证书失败", e);
        }
    }

    /**
     * <desc>
     *      下载证书
     * </desc>
     *
     * @param operateLicenseDTO 查询参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/9/25
     */
    @UnAuthAccessRequired
    @RequestMapping(value = "/online/licenseDownload", method = RequestMethod.POST)
    public Object downloadLicense(OperateLicenseDTO operateLicenseDTO, HttpServletRequest request){
        try {
            operateLicenseDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateLicenseDTO.class, request);
            if (operateLicenseDTO == null || StringUtils.isBlank(operateLicenseDTO.getProjectId()) || operateLicenseDTO.getLicenseType() == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String ip = HttpProtocolUtil.getIpAddr(request);
            operateLicenseDTO.setIp(ip);
            Map<String, Object> resultMap = iOperateProjectServiceClient.licenseDownload(operateLicenseDTO);
            if (resultMap == null){
                return new MessageVO(OperateErrorCodeEnum.OPERATE_NONE_LICENSE_ERROR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目_在线查询证书网站】下载证书失败", e);
        }
    }

    /**
     *<desc>
     * 导出安全证书
     *</desc>
     *
     * @Author  chengshican
     * @Date   2020-09-25 16:16
     * @Param    项目id projectId
     * @Return
     * @Exception
     *
     */
    @LoggerInfo(operateDesc = LogDescConstant.OPERATE_EXPORT_CERTIFICATE_INFO_LOG_DESC)
    @RequestMapping(value = "/export/certificate",method =RequestMethod.POST)
    public Object getExportCertificate(OperateLicenseDTO operateLicenseDTO, HttpServletRequest request){
        try{
            operateLicenseDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateLicenseDTO.class, request);
            String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
            if (operateLicenseDTO == null || StringUtils.isBlank(operateLicenseDTO.getProjectId()) || StringUtils.isBlank(myUserName)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String ip = HttpProtocolUtil.getIpAddr(request);
            operateLicenseDTO.setIp(ip);
            operateLicenseDTO.setLoginUserId(myUserName);
            Map<String, Object> certificate = iOperateProjectServiceClient.licenseDownload(operateLicenseDTO);
            if (certificate == null){
                return new MessageVO(OperateErrorCodeEnum.OPERATE_NONE_LICENSE_ERROR.getErrorCode());
            }
            Map<String, Object> map = new HashMap<>();
            map.put("certificateInfo",certificate.get("certificateInfo")+"");
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目_导出安全证书】导出安全证书失败", e);
        }

    }

    /**
     * <desc>
     *      在线保存电脑特征码
     * </desc>
     *
     * @param operateLicenseDTO 特征码相关信息
     * @return
     * @Author Zhu.yj
     * @createDate  2020/9/17
     */
    @UnAuthAccessRequired
    @RequestMapping(value = "/online/savePCInfo", method = RequestMethod.POST)
    public Object onlineSavePCInfo(OperateLicenseDTO operateLicenseDTO, HttpServletRequest request){
        try {
            operateLicenseDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateLicenseDTO.class, request);
            if (operateLicenseDTO == null || StringUtils.isBlank(operateLicenseDTO.getPcInfo()) || StringUtils.isBlank(operateLicenseDTO.getProjectId())
                    || StringUtils.isBlank(operateLicenseDTO.getOperateFunction()) || StringUtils.isBlank(operateLicenseDTO.getOperateWay())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Map<String, Object> resultMap = new HashMap<>();
            String ip = HttpProtocolUtil.getIpAddr(request);
            operateLicenseDTO.setIp(ip);
            return iOperateProjectServiceClient.savePcInfo(operateLicenseDTO);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目_证书管理】保存电脑特征码失败", e);
        }
    }

    /**
     * <desc>
     *      同步项目与特征码对应记录表数据()
     * </desc>
     *
     * @Author Zhu.yj
     * @createDate  2020/10/13
     */
    @UnParamEncrypt
    @UnAuthAccessRequired
    @PostMapping("synchronizeData")
    public Object synchronizeData(){
        try{
            int rows = iOperateProjectServiceClient.synchronizeData();
            if (rows == OperateErrorCodeEnum.OPERATE_SYNC_DATA_EXIST_ERR.getCode()){
                return new MessageVO(OperateErrorCodeEnum.OPERATE_SYNC_DATA_EXIST_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), rows);
        }catch (Exception e){
            throw new DataAccessException("【运营_项目管理synchronizeData】同步项目与特征码对应记录表数据失败", e);
        }
    }
}
